package com.autonavi.collapse.task;

import com.autonavi.collapse.task.model.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TaskExecutorContainer {

    private TaskExecutorManager taskExectorManager;

    private Map<String, TaskExecutor> runningTasks = new ConcurrentHashMap<>();

    public List<TaskConfig> create(TaskTemplate taskTemplate) {
        if (taskTemplate == null) {
            return null;
        }
        TaskFactory taskFactory = taskExectorManager.find(taskTemplate.getType());
        if (taskFactory != null) {
            return taskFactory.generateTask(taskTemplate);
        }
        return null;
    }

    public TaskResult execute(String type, TaskContext context) {
        TaskConfig taskConfig = context.getTaskConfig();
        String id = taskConfig.getId();
        TaskFactory taskFactory = taskExectorManager.find(type);
        if (taskFactory != null) {
            TaskExecutor taskExecutor = taskFactory.create(context);
            if (taskExecutor != null) {
                try {
                    TaskExecutor origin = runningTasks.putIfAbsent(id, taskExecutor);
                    if (origin == null) {
                        return taskExecutor.process(context);
                    }
                    return null;
                }finally {
                    runningTasks.remove(id);
                }
            }
        }
        return new TaskResult(TaskResultStatus.UNSUPPORTED, taskConfig, String.format("Task type %s is not supported"));
    }

    public void interrupt(String id) throws InterruptedException {
        TaskExecutor taskExecutor = runningTasks.get(id);
        if (taskExecutor != null) {
            taskExecutor.interrupt();
        }
    }

    public boolean isRunning(String id) {
        return runningTasks.containsKey(id);
    }

    public void setTaskExectorManager(TaskExecutorManager taskExectorManager) {
        this.taskExectorManager = taskExectorManager;
    }

    public int getRunningTaskSize() {
        return runningTasks.size();
    }
}
